<template>
  <div class="hello">
    <input
      type="file"
      placeholder=""
      placeholder-class="input-placeholder"
      @change="handleInputFileChange"
    />
    <div>
      <div class="book-item" v-for="book in list" :key="book.uuid" @click="handleReadBook(book)">
        <div class="cover">
          <img :src="book.cover"  />
        </div>
        <div class="info">
          <div class="title">{{ book.title }}</div>
          <div class="author">{{ book.author }}</div>
          <div class="route">阅读进度 0%</div>
        </div>
      </div>
      <div v-if="reading" class="epub-reader">
        <epub-reader :ebook="currentBook" />
      </div>
    </div>
  </div>
</template>

<script>
import Epub from '../../../packages/ebook-epub'
import EpubReader from './EpubReader.vue'

var zip

export default {
  components: { EpubReader },
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      files: [],
      reading: false,
      ebook: {},
      currentBook: undefined,
      list: []
    }
  },
  methods: {
    async handleInputFileChange(evt) {
      const file = evt.target.files[0]
      console.log(file)
      var res = await Epub.parseFromData(file, {})
      if(res._zip) {
        zip = res._zip
        this.files = Object.keys(res._zip.files)
        var info = res.info
        this.list.push(info)
        this.ebook[info.uuid] = res
      }
    },
    async linkTo(fileName) {
      var blob = await zip.file(fileName).async('blob')
      const blobUrl = URL.createObjectURL(blob)
      var a = document.createElement('a')
      a.href = blobUrl
      a.target = "__blank"
      a.download = fileName
      a.click()
    },
    handleReadBook(book) {
      this.currentBook = this.ebook[book.uuid]
      this.reading = true
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
body {
  margin: 0;
  padding: 0;
}

.book-item {
  display: flex;
  flex-direction: row;
  margin: 0px 15px;
  padding: 10px 0;
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
  cursor: pointer;
}

.cover {
  width: 60px;
  height: 83px;
  margin-right: 10px;
}

.cover img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 2px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.info {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}

.title {
  font-weight: bold;
  font-size: 18px;
  color: #333;
  margin-bottom: 3px;
}

.author {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.route {
  font-size: 12px;
  color: #333;
}

.epub-reader {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  background-color: #fff;
}
</style>
